package ycl.base.service.impl;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import ycl.base.entity.PublicFiles;
import ycl.base.mapper.PublicFilesMapper;
import ycl.base.req.PublicFilesReq;
import ycl.base.res.PublicFilesRes;
import ycl.base.service.PublicFilesService;
import ycl.base.utils.UploadFileData;
import ycl.common.base.service.impl.BaseServiceImpl;
import ycl.common.result.REnum;
import ycl.common.exception.CustomException;
import ycl.common.models.req.IdNameReq;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 用户文件管理 服务实现层
 *
 * @author ycl
 * @date 2022/7/6 0006 11:47:02
 */
@Service
@Slf4j
public class PublicFilesServiceImpl extends BaseServiceImpl
		<PublicFilesMapper, PublicFiles, PublicFilesReq, PublicFilesRes>
		implements PublicFilesService {

	@Resource
	private PublicFilesMapper publicFilesMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void upload(UploadFileData uploadData, MultipartFile file) {
		Long size = uploadData.getFileSize();
		String crypto = uploadData.getCrypto();
		String suffix = uploadData.getSuffix();
		String publicOutPath = uploadData.getPublicOutPath();
		String fileUuidName = uploadData.getFileUuidName();
		PublicFiles insert = new PublicFiles()
				.setName(fileUuidName)
				.setSuffix(suffix)
				.setCrypto(crypto)
				.setFileSize(size)
				.setPath(publicOutPath)
				.setCreateTime(LocalDateTime.now());
		publicFilesMapper.insert(insert);

		File publicFile = new File(publicOutPath, fileUuidName);
		FileUtil.mkParentDirs(publicFile);
		try {
			file.transferTo(publicFile);
		} catch (IOException e) {
			log.error("FilesServiceImpl . upload2 . exception");
			log.error("{}", e.getMessage(), e);
			publicFile.delete();
			throw new CustomException(REnum.CUSTOM_FILE_UPLOAD_EXCEPTION);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateAlias(HttpServletRequest request, IdNameReq req) {
		publicFilesMapper.updateAlias(req.getId(), req.getName());
	}
}
